import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/json")
class User{
    //这里的属性要么为public修饰，如果是private修饰一定需要提供getter和setter方法
    //同时类的属性名称一定需要和json的键值对的键名称和类型匹配（这就需要前端和后端的相互配合“约定前后端交互接口”）
    public String name;
    public String password;
}
public class JsonServlet extends HttpServlet {
    //客户端body按照json格式进行传输
    //json格式为：
    //{
    //name:"lcc",
    //password:"123"
    //}
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        //ObjectMapper的readValue方法将请求输入的json格式映射为对象
        User user = objectMapper.readValue(req.getInputStream(),User.class);
        System.out.println("name=" + user.name + "," + "password:" + user.password);
        //也可以将对象映射为字符串，通过ObjectMapper的writeVlueAsString方法---》一个类两个方法
        String userString = objectMapper.writeValueAsString(user);
        System.out.println("userString:" + userString);
        resp.getWriter().write("ok");
    }
}
